<template>
  <view class="u-page">
    <view class="cell-page">
      <view class="u-page__item">
        <text class="u-page__item__title">基础信息</text>
        <u-cell-group>
          <u-cell title="集资参与人姓名" :value="form.name" v-if="oneself"></u-cell>
          <u-cell title="继承权利人姓名" :value="form.name1" v-if="!oneself"></u-cell>
          <u-cell title="集资参与人证件号" :value="form.idCardNo" v-if="oneself"></u-cell>
          <u-cell title="继承权利人证件号" :value="form.idCard1No" v-if="!oneself"></u-cell>
          <u-cell title="集资参与人银行卡号" :value="form.bankCardNo" v-if="oneself"></u-cell>
          <u-cell title="继承权利人银行卡号" :value="form.bankCard1No" v-if="!oneself"></u-cell>
		  <u-cell title="联系电话" :value="form.contactNumber"></u-cell>
        </u-cell-group>
      </view>
      <view class="u-page__item">
        <text class="u-page__item__title">集资信息</text>
        <u-cell-group>
          <u-cell title="实际投入金额" :value="formatNum(form.actualInvestmentAmount)"></u-cell>
          <u-cell title="实际返本利金额" :value="formatNum(form.actualAmountOfPrincipalAndInterestReturned)"></u-cell>
          <u-cell title="实际损失金额" :value="formatNum(form.actualLossAmount)"></u-cell>
          <u-cell title="实际应返还损失额" :value="formatNum(form.actualAmountOfLossToBeReturned)"></u-cell>
        </u-cell-group>
      </view>
    </view>
    <u-row class="w-100 mt-4" justify="center">
      <u-col span="5" justify="center">
        <u-button shape="circle" @click="toPreYxPage"><view>上一步</view></u-button>
      </u-col>
      <u-col span="5" justify="center">
        <u-button type="primary" shape="circle" @click="goSign"><view>拍照签名</view></u-button>
      </u-col>
    </u-row>
    <u-row class="mt-4">
      <u-col span="12"><uni-steps :options="stepList" :active="currentStepIndex"></uni-steps></u-col>
    </u-row>
    <u-popup :show="signShow" :round="10" mode="center"><Autograph ref="sign" @back="confirm"></Autograph></u-popup>
  </view>
</template>

<script>
import { baseFont, yxStepKey } from '@/common/config.js';
import { getAccessToken, getVerifyToken, updateImageToRepository, realNameAuth, match } from '@/common/baiduApi.js';
import Autograph from '@/component/autograph/autograph.vue';
import { pathToBase64 } from 'image-tools';
import { formatReserve } from '@/util/common.js';
import { checkSave } from '@/common/api/yxRegister.js';

export default {
  components: {
    Autograph,
  },
  data() {
    return {
      preStep: yxStepKey.step2,
      currentStep: yxStepKey.step3,
      nextStep: yxStepKey.step3,
      labelStyle: { fontSize: baseFont + 'upx', marginBottom: '20upx' },
      form: {
        name: null,
        idCardNo: null,
        idCardPositiveUrl: null,
        idCardFaceUrl: null,
        idCardBackUrl: null,
        bankCardPositiveUrl: null,
        bankCardBackUrl: null,
        bankCardNo: null,
        name1: null,
        idCard1No: null,
        idCard1PositiveUrl: null,
        idCard1FaceUrl: null,
        idCard1BackUrl: null,
        bankCard1PositiveUrl: null,
        bankCard1BackUrl: null,
        bankCard1No: null,
        deathCertificateUrl: null,
        acts: null,
        relation: null,
        registeredResidence: [],
        bills: [],
        videoUrl: null,
        videoFaceUrl: null,
        sign: null,
        oneself: true,
        sign: null,
        step: 3,
        contactNumber: null,
      },
      signShow: false,
      cardFaceBase64: '',
    };
  },
  computed: {
    currentStepIndex() {
      return this.oneself ? 2 : 3;
    }
  },
  onLoad(options) {
    this.checkYxPage(options);
    const res = this.$getYxInfo(this.idCard);
    this.form.actualInvestmentAmount = res.step1.actualInvestmentAmount;
    this.form.actualAmountOfPrincipalAndInterestReturned = res.step1.actualAmountOfPrincipalAndInterestReturned;
    this.form.actualLossAmount = res.step1.actualLossAmount;
    this.form.actualAmountOfLossToBeReturned = res.step1.actualAmountOfLossToBeReturned;
    this.form.oneself = this.oneself;
    this.form.name = res.step1.name;
    this.form.idCardNo = res.step1.idCardNo;
    this.form.bankCardNo = res.step2.bankCardNo;
    this.form.idCardPositiveUrl = res.step1.idCardPositiveUrl;
    this.form.idCardFaceUrl = res.step1.idCardFaceUrl;
    this.form.idCardBackUrl = res.step1.idCardBackUrl;
    this.form.bankCardPositiveUrl = res.step2.bankCardPositiveUrl;
    this.form.contactNumber = res.step2.contactNumber;
    if (this.oneself) {
      this.cardFaceBase64 = res.step1.idCardFaceBase64;
    } else {
      this.form.name1 = res.step1_5.name1;
      this.form.idCard1No = res.step1_5.idCard1No;
      this.form.bankCard1No = res.step1_5.bankCard1No;
      this.cardFaceBase64 = res.step1_5.idCard1FaceBase64;
      this.form.bankCard1No = res.step2.bankCard1No;
      this.form.idCard1PositiveUrl = res.step1.idCard1PositiveUrl;
      this.form.idCard1FaceUrl = res.step1_5.idCard1FaceUrl;
      this.form.idCard1BackUrl = res.step1_5.idCard1BackUrl;
      this.form.deathCertificateUrl = res.step1_5.deathCertificateUrl;
      this.form.authenticAct = res.step1_5.authenticAct;
      this.form.relation = res.step1_5.relation;
      this.form.registeredResidence = res.step1_5.registeredResidence;
      this.form.bankCard1PositiveUrl = res.step2.bankCard1PositiveUrl;
    }
    this.form.bills = res.step2.bills;
    if (options.check) {
      let that = this;

      //关闭页面滚动，
      that.stop();

      that.signShow = true;
      that.$nextTick(() => {
        that.$refs.sign.autograph();
      });
    }
  },
  methods: {
    // 阻止页面滚动
    stop() {
      var box = function(e) {
        passive: false;
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener('touchmove', box, false);
    },
    // 允许页面滚动
    move() {
      var box = function(e) {
        passive: false;
      };
      document.body.style.overflow = ''; // 出现滚动条
      document.removeEventListener('touchmove', box, false);
    },
    formatNum(num) {
      if (num) {
        return formatReserve(num);
      } else {
        return null;
      }
    },
    confirm(bool) {
      // 签名结束，放开页面滚动
      this.move();

      this.signShow = false;
      if (bool) {
        this.form.sign = this.$refs.sign.signature;
        checkSave(this.form).then(res => {
          this.toYxResult(res.data.state,res.data.reason,this.idCard)
        });
      }
    },
    doSign() {
      let that = this;
      that.signShow = true;
      that.$nextTick(() => {
        that.$refs.sign.autograph();
      });
    },
    async goSign() {
      const idCard = this.idCard;
      this.saveYxInfo(idCard);
      let that = this;
      that.accessToken = await getAccessToken();
      that.verifyToken = await getVerifyToken(that.accessToken);
      that.face1 = this.cardFaceBase64.replace(/^data:image\/\w+;base64,/, '');
      // let imgRes = await updateImageToRepository(baseImage, accessToken, verifyToken);
      setTimeout(() => {
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['camera'],
          success(res) {
            // uni.$u.toast('选择完图片');
            uni.showLoading({
              title: '处理中，请稍后...',
            });
            // const tempFilePaths = res.tempFilePaths;
            // pathToBase64(tempFilePaths[0])
            // .then(path => {
            // 	// uni.$u.toast('转base64');
            // 	that.baseImage2 = path.replace(/^data:image\/\w+;base64,/, "");
            // 	if(that.baseImage2){
            // 		// uni.$u.toast('1比1');

            // 	}
            // })
            // .catch(error => {
            // 	uni.showToast({
            // 					title: '上传失败',
            // 					duration:850
            // 				});
            // })
            let file = res.tempFiles[0];
            if (file.size > 1024 * 1024 * 4) {
              that.compressImage(file);
            } else {
              const tempFilePaths = res.tempFilePaths;
              pathToBase64(tempFilePaths[0]).then(path => {
                that.baseImage2 = path.replace(/^data:image\/\w+;base64,/, '');
                if (that.baseImage2) {
                  // uni.$u.toast('1比1');
                  that.goMath(that.face1, that.baseImage2);
                }
              });
            }
          },
          fail: error => {
            uni.$u.toast(JSON.stringify(error));
          },
        });
      });
    },
    goMath(face1, face2) {
      let that = this;
      match(face1, face2, that.accessToken).then(res => {
        if (res.data.error_code == 0) {
          // uni.$u.toast('一比一');
          uni.showLoading({
            title: '正在人像一比一，请稍后...',
          });
          if (res.data.result.score >= 60) {
            that.uploadImgRepo(face2);
          }
        } else {
          uni.$u.toast('请确保本人操作！');
        }
      });
    },
    uploadImgRepo(base64) {
      // uni.$u.toast('入库');
      uni.showLoading({
        title: '正在人像入库，请稍后...',
      });
      let that = this;
      const sucess=this.getYxBaiduSuccessPage()
      updateImageToRepository(base64, that.accessToken, that.verifyToken).then(imgRes => {
        if (imgRes.data.success) {
          // uni.$u.toast('打开');
          // let sucess = encodeURIComponent('http://[2409:8a1a:549:efc0:f96f:ce63:4133:ae98]/pages/yx/step3?idCard=' + that.idCard + '&check=true');
          // let sucess = encodeURIComponent('http://116.204.76.200:8082/pages/yx/result?idCard=' + that.idCard);
          // let sucess = encodeURIComponent(
          //   'http://cfb.wuxucloud.cn:8088/pages/yx/step3?idCard=' + that.idCard + '&check=true'
          // );
          uni.$u.toast('打开活体检测');
          realNameAuth(that.verifyToken, sucess, '');
          // .then(() => {
          // that.signShow = true;
          // that.$nextTick(() => {
          // 	that.$refs.sign.autograph();
          // 	that.form.sign = that.$refs.sign.signature;
          // 	checkSave(that.form).then(res => {

          // 	})
          // })
          // })
        } else {
          uni.$u.toast(imgRes.data.message);
        }
      });
    },
    compressImage(urlData) {
      // uni.$u.toast('压缩');
      // uni.showLoading({
      // 	title: '压缩中...'
      // })
      uni.showLoading({
        title: '正在压缩人像，请稍后...',
      });
      let _this = this;
      uni.getImageInfo({
        src: urlData.path,
        success(res) {
          let originWidth = res.width; //图片原始宽
          let originHeight = res.height; //图片原始高
          let maxWidth = 800;
          let maxHeight = 800;
          let img = new Image();
          img.src = res.path;
          let canvas = document.createElement('canvas');
          let ctx = canvas.getContext('2d');
          // 目标尺寸
          let targetWidth = originWidth;
          let targetHeight = originHeight;
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }

          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 图片压缩
          ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
          // canvas对图片进行缩放 0.3是我定义的图片质量，
          let base64 = canvas.toDataURL(urlData.type, 0.3);

          // uni.hideLoading()
          _this.goMath(_this.face1, base64.split(',')[1]);
        },
        fail() {
          uni.showModal({
            title: '提示',
            content: '图片压缩失败',
            showCancel: false,
          });
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.cell-page {
  padding-bottom: 20px;
}
</style>
